package org.spawndb.impl.hssql;


import org.spawndb.ISpawnDBManager;
import org.apache.log4j.Logger;
import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl.AclFormatException;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class HSSQLManager implements ISpawnDBManager {
    private HsqlProperties properties;
    private Server server;
    private Map<String,String> options= new HashMap<String,String>();
    private String baseDir = System.getProperty("user.home")+"/db/hssql";
    private String dataDir;
    private boolean running=false;
    private static final Logger log = Logger.getLogger("HSSQLManager");
    private static String dbname="test";
    private static int serverPort=9001;

    public HSSQLManager(){
    }

    @Override
    public void setBaseDir(String baseDir) {
        this.baseDir=baseDir;
    }

    @Override
    public void setDataDir(String dataDir) {
        this.dataDir=dataDir;
    }

    @Override
    public void setDBProperties(Map options){
        this.options=options;
    }

    public void start() throws Exception {
        if(running) throw new Exception("db is already running");
        log.info("Starting HSQL server...");
        if(dataDir==null)
            dataDir = baseDir+ "/data";
        File dbRootDir = new File(dataDir);
        if(dbRootDir.exists()) dbRootDir.mkdirs();
        if(options.get("db.name")!=null) dbname = options.get("db.name");
        if(options.get("server.port")!=null) serverPort = Integer.valueOf(options.get("server.port"));
        server = new Server();
        server.setPort(serverPort);
        server.setDatabaseName(0,dbname);
        server.setDatabasePath(0,"file://"+dataDir+"/"+dbname);
        try{
            server.setProperties(properties);
            server.setDaemon(true);
            server.start();
        }
        catch(AclFormatException afe){
            log.error("Error starting HSQL server.", afe);
        }
        catch (IOException e) {
            log.error("Error starting HSQL server.", e);
        }
        running=true;
        System.out.println("HSSQL is running.");
    }



    public void stop() throws Exception {
        if(!running) throw new Exception("db is already stopped");
        log.info("Stopping HSQL server...");
        if(server == null) return;
        server.stop();
        running=false;
    }


    @Override
    public File getDataDir() {
        if(dataDir==null)
            dataDir = baseDir+"/data";
        return new File(dataDir);
    }

    @Override
    public File getBaseDir() {
        return new File(baseDir);
    }

    @Override
    public String getDBVendor() {
        return "hsssql";
    }

}